define(['zepto',"common/mcommon"],
	function($,mcommon){
		var validatePlugin = function (elem,callback,options) {
			var _this = this;
	        _this.elem = elem;
	        _this.opt = {
	            //提示信息
	            regMsg:{
	            	email   	: '邮箱地址格式有误',
	            	num     	: '请填写数字',
	            	letter      : '请输入字母',
	            	chinese     : '请填写中文',
	            	mobile   	: '手机号码格式有误',
	           		idcard      : '身份证号码格式有误',      
	            	numletter 	: '应该为数字和字母的组合字符',
	            	passport    : '护照格式有误',
	            	numwith2float: '请输入最多有两位小数的数字',
	            	amount       : '金额格式不正确',
	            	nickname     : '昵称必须是数字字母中文的组合',
	            },
	            reg:{
	            	email 		: /^\w+\@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/i,   //验证邮箱
	            	num         : /^\d+$/,                                 //验证数字
	            	letter      : /^[A-Za-z]*$/,						   //验证字母
	            	chinese     : /^[\u4E00-\u9FA5]+$/,                    //验证中文
	            	mobile      : /^1[13456789]{1}[0-9]{9}$/,              //验证手机
	            	idcard      : /^\d{14}\d{3}?\w$/,                      //验证身份证
	            	numletter   : /^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]+$/, 			     //验证数字和字母
	            	passport    : /^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$/, //验证护照
	            	numwith2float: /^\d+\.?\d{0,2}$/,                                        //带两位小数点数字验证
	            	amount       : /^-{0}(([1-9][\d]{0,7})(\.[0-9]{1,2})?|(0\.[1-9]{1,2})|(0\.0[1-9]{1})|(0\.[1-9]{1}0))$/,   //金额验证（不能为0）
	            	nickname	:/^[A-Za-z0-9\u4E00-\u9FA5]+$/
	            },
	            tipMsg_require :'必须输入'
	        };
	        
	        _this.elemType = $(elem).attr("type");
	        _this.elemTag = elem.tagName.toLowerCase();
	        if(_this.elemTag === 'form'){
	        	_this.validateForm(callback,options);
	        }else{
	        	var elementInfoGrp =_this.elementsGroup(elem);
	        	_this.result = true;
	        	if(elementInfoGrp){
	        		$(elementInfoGrp).each(function(){
	        			if(_this.result){
	        				_this.result = _this.validate(this)&& (options&&options.validate?options.validate.call(this):true);
	        			}
	        		});
	        	}
	        }
	        return _this;
	    };
		
	    validatePlugin.prototype={
	    	
	    	validateForm:function(callback,options){
	    		var _this = this,elements;
	    		
	    		var defaults = {
					validate: function() { return true; }
				};

				var params =  $.extend(defaults,options||{});

				elements = $(_this.elem).find("input,select,textarea");

				//绑定submit
	    		$(_this.elem).on('submit',function(){
	    			if(_this.formCheck(elements) && params.validate.call(this)){
	    				//form submit时，会存在需要直接提交到后台的情况，所以添加了directSubmit属性，如果该属性为1直接提交该表单
	    				var isDirectSubmit = $(this).attr("directSubmit");
	    				if(isDirectSubmit && isDirectSubmit==="1"){
	    					return true;
	    				}else{
	    					var ajaxParams = {};
		    				ajaxParams.url = _this.elem.getAttribute("action");
		    				var data;
		    				$(_this.elementsInfos).each(function(){
		    					if(this.val&&this.nm){
		    						if(!data) data ={};
		    						data[this.nm] = this.val;
		    					}
		    				});
		    				data?ajaxParams.data = data:true;
		    				$.isFunction(callback)?ajaxParams.error=ajaxParams.success=callback:true;
		    				mcommon.ajax(ajaxParams);
	    				}
	    			}
	    			return false;
	    		});
	    		
	    	},
	    	formCheck:function(elements){
	    		var _this = this;
	    		if (elements.size && elements.size() == 1 && elements.get(0).tagName.toLowerCase() == "form") {
					elements = elements.find("input,select,textarea");	
				} else if (elements.tagName && elements.tagName.toLowerCase() == "form") {
					elements = $(elements).find("input,select,textarea");	
				}
				var flg=true;
				if(elements){
					//获得元素验证信息
					_this.elementsInfos = _this.elementsGroup(elements);
					$(_this.elementsInfos).each(function(){
						if(flg&&!_this.validate(this)){
							flg = false;
						}
					});
				}
				return flg;
	    	},
	    	/*
	    		元素进行分组(将单选和复选的多个选项合并为1个独立的元素)
	    		组合元素的验证信息
	    	 */
	    	elementsGroup:function(elements){
	    		var _this = this,elementInfoGrp = [];
	    		if(!elements.length){
	    			var tempArray = [];
	    			tempArray.push(elements);
	    			elements = tempArray;
	    		}
	    		$(elements).each(function(){
	    			var el = this,type = el.getAttribute?el.getAttribute("type"):"",tag = el.tagName.toLowerCase();
	    			
	    			//去除多余字符
	    			if (type) {
						var typeReplace = type.replace(/\W+$/, "");	
						if ( type != typeReplace) {
							try { el.type = typeReplace; } catch(e) {}
						}
						type = typeReplace;
					}
					
					//获得中文名称
					var cnNm = $('label[for="'+el.id+'"]').text();
					cnNm = cnNm || "";

					//元素基本信息
					elementInfo = {nm:el.name,id:el.id,type:type,tagNm:tag,element:el,cnNm:cnNm};

					//单选复选控制
					if(tag==='input'){
						if(type==='checkbox' || type==='radio'){
							
							//将单选和复选的多个选项合并为1个独立的元素
							var isHad = $(elementInfoGrp).filter(function(){
								if(this.nm == el.name){
									return true;
								}
							}).length>0;
							if(!isHad){
								var eleCheckboxs = el.name? $("input[type='"+type+"'][name='"+ el.name +"']"): $(el);
								elementInfo.element= [];
								$(eleCheckboxs).each(function(){
									elementInfo.element.push(this);
								})
							}else{
								elementInfo = null;
							}
						}
					}

					//组合元素的验证信息
					if(elementInfo){

						// 获得元素的值
						var _val;
			    		if($.isArray(elementInfo.element)){
			    			var val = [];
			    			$(elementInfo.element).each(function(){
			    				if($(this).prop("checked")){
			    					val.push($.trim($(this).val()));
			    				}
			    			});
			    			val.length==0?"":(_val=val);
			    		}else{
			    			_val = $.trim($(elementInfo.element).val());
			    		}
			    		elementInfo.val = _val;

						//单选复选时,使用第一个元素的验证信息
						if($.isArray(elementInfo.element)){
							el = elementInfo.element[0];	
						}
						elementInfo.validate = {};
						el.hasAttribute("require")?elementInfo.validate.require=true:"";
						el.hasAttribute("mobile")?elementInfo.validate.mobile=true:"";
						el.hasAttribute("email")?elementInfo.validate.email=true:"";
						el.hasAttribute("number")?elementInfo.validate.num=true:"";
						el.hasAttribute("letter")?elementInfo.validate.letter=true:"";
						el.hasAttribute("numletter")?elementInfo.validate.numletter=true:"";
						el.hasAttribute("chinese")?elementInfo.validate.chinese=true:"";
						el.hasAttribute("idcard")?elementInfo.validate.idcard=true:"";
						el.hasAttribute("numwith2float")?elementInfo.validate.numwith2float=true:"";
						el.hasAttribute("amount")?elementInfo.validate.amount=true:"";
						el.hasAttribute("nickname")?elementInfo.validate.nickname=true:"";
						$(el).attr("eqTo")?elementInfo.validate.eqTo=$(el).attr("eqTo"):"";
						$(el).attr("minLen")?elementInfo.validate.minLen=$(el).attr("minLen"):"";
						$(el).attr("maxLen")?elementInfo.validate.maxLen=$(el).attr("maxLen"):"";
						$(el).attr("minVal")?elementInfo.validate.minVal=$(el).attr("minVal"):"";
						$(el).attr("maxVal")?elementInfo.validate.maxVal=$(el).attr("maxVal"):"";
						elementInfoGrp.push(elementInfo);
					}
	    		});
				return elementInfoGrp;
	    	},
	    	//通过元素信息，进行验证
	    	validate:function(elementInfo){
	    		var _this = this;
	    		var _res = true;
	    		for(var i in elementInfo.validate){
	    			if(!_res) break;
	    			if(!elementInfo.validate[i]){
	    				continue;
	    			}
	    			if(_this.opt.reg[i]){
	    				if(!_this.regmatch(elementInfo.val, this.opt.reg[i])){
	    					_res = false;
	    					_this.showErrorMsg(elementInfo,_this.opt.regMsg[i],true,"");
	    				}
	    			}else{
	    				if(i==='require'){
	    					if(!elementInfo.val){
	    						_res = false;
	    						_this.showErrorMsg(elementInfo,_this.opt.tipMsg_require,true,"null");
	    					}
	    				}else if(i==='minLen'){
	    					_res = _this.checkLength(true,parseInt(elementInfo.validate[i]),elementInfo);
	    				}else if(i==='maxLen'){
	    					_res = _this.checkLength(false,parseInt(elementInfo.validate[i]),elementInfo);
	    				}else if(i==='minVal'){
							_res = _this.checkVal(true,elementInfo.validate[i],elementInfo);
	    				}else if(i==='maxVal'){
	    					_res = _this.checkVal(false,elementInfo.validate[i],elementInfo);
	    				}else if(i==='eqTo'){
	    					_res = _this.checkEqual(elementInfo,elementInfo.validate[i]);
	    				}
	    			}
	    		}
	    		return _res;
	    	},
	    	regmatch:function(value, regExp) {
	    		try{
	    			if (value !== "") {
	                	return regExp.test(value);
	            	}
	    		}catch(e){
	    			//console.info(e);
	    		}
	            return true;
	        },
	    	checkLength:function(isLeast,length,elementInfo){
	    		var _this = this,msg;
	    		if(elementInfo.val){
	    			var inputLength = elementInfo.val.length;
		    		if(isLeast){
		    			//最小时
		    			if(length<=inputLength)return true;
		    			msg = "不能少于"+length;
		    		}else{
		    			//最大时
		    			if(length>=inputLength)return true;
		    			msg = "不能多于"+length;
		    		}	
	    		}
	    		msg = msg + ($.isArray(elementInfo.val)?"项":"位");
	    		_this.showErrorMsg(elementInfo,msg,true,"len");

	    		return false;
	    	},
	    	checkEqual:function(elementInfo,compElement){
	    		var _this = this;

	    		var compInfo = $(_this.elementsInfos).filter(function(){
	    			if(this.id==compElement){
	    				return true;
	    			}
	    		});
	    		if(compInfo) compInfo = compInfo[0];

	    		if(elementInfo.val != compInfo.val){
	    			var msg = elementInfo.cnNm + "与"+compInfo.cnNm+"不一致";
	    			_this.showErrorMsg(elementInfo,msg,true,"eq");
	    			return false;
	    		}
	    	},
	    	checkVal:function(isMin,val,elementInfo){
	    		if($.isArray(elementInfo.val))return true;
	    		var _this = this,msg;
	    		if(elementInfo.val){
	    			var compVal = new Number(val);
	    			var elementVal = new Number(elementInfo.val);
	    			if(isNaN(compVal)||isNaN(elementVal)) return;
		    		if(isMin){
		    			//最小
		    			if(compVal<=elementVal) return true;
		    			msg = "不能小于"+val;
		    		}else{
		    			//最大时
		    			if(compVal>=elementVal)return true;
		    			msg = "不能大于"+val;
		    		}
	    		}
	    		_this.showErrorMsg(elementInfo,msg,true,"val");
	    		return false;
	    	},
	    	getMsgByType:function(elementInfo,type){
	    		var element = elementInfo.element;
	    		if($.isArray(elementInfo.element)){
	    			element = elementInfo.element[0];
	    		}
	    		if(type) type = type +"Msg";
	    		var msg = $(element).attr(type);
	    		if(msg) return msg;
	    		msg = $(element).attr("msg");
	    		return $.trim(msg);
	    	},
	    	showErrorMsg:function(elementInfo,msg,showNm,type){
	    		var _this = this;
	    		var custMsg = _this.getMsgByType(elementInfo,type);
	    		msg = custMsg?custMsg:msg;
	    		msg = showNm?elementInfo.cnNm+msg:msg;
				mcommon.toast(msg);
				if($.isArray(elementInfo.element)){
	    			elementInfo.element[0].focus();
	    			elementInfo.element[0].select();
	    		}else{
	    			elementInfo.element.focus();
	    			elementInfo.element.select();
	    		}
	    	}
	    }


		$.fn.validate = function (callback,options) {
			if(this.length==1){
				return new validatePlugin(this[0],callback,options);	
			}else{
				$(this).each(function(){
					return	new validatePlugin(this[0],callback,options);		
				})
			}
	    };
	    return $;
	}
);